package com.lhl.netty.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by Administrator on 2016/4/28.
 */
public class NetDecoder extends ByteToMessageDecoder { // (1)
    private final static Logger logger = LoggerFactory.getLogger(NetDecoder.class);

    private boolean foundStart = false;
    private boolean foundType = false;
    private boolean foundLength = false;
    private String curStart=null;
    private NetMessageType curType = null;
    private Integer curLength = 0;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // (2)
        if(!foundStart){
            if (in.readableBytes() < 2) { //不够2个字符就继续等待
                logger.debug("收到长度："+in.readableBytes()+",不足2继续等待");
                return; // (3)
            }else if(in.readableBytes() >= 2){
                curStart =  in.readBytes(2).toString(CharsetUtil.UTF_8);
                foundStart = true;
            }
        }
        if(!foundType){
            if (in.readableBytes() < 4) { //不够4个字符就继续等待
                logger.debug("收到长度："+in.readableBytes()+",不足4继续等待");
                return; // (3)
            }else if(in.readableBytes() >= 4){
                int typeIndex = in.readBytes(4).readInt();
                if(typeIndex>=NetMessageType.values().length){
                    logger.debug("解析消息失败，未知类型："+typeIndex);
                }else{
                    curType =  NetMessageType.values()[typeIndex];
                    foundType = true;
                    logger.debug("收到消息类型："+curType.name());
                }
            }
        }
        if(!foundLength){
            if (in.readableBytes() < 4) { //不够4个字符就继续等待
                logger.debug("收到长度："+in.readableBytes()+",不足4继续等待");
                return; // (3)
            }else if(in.readableBytes() >= 4){
                curLength =  in.readBytes(4).readInt();
                foundLength = true;
                logger.debug("解析到消息长度："+curLength);
            }
        }

        if (in.readableBytes() < curLength) { //不够curLength个字符就继续等待
            logger.debug("收到长度："+in.readableBytes()+",不足"+curLength+"继续等待");
            return; // (3)
        }else if(in.readableBytes() >= curLength){
            String content = in.readBytes(curLength).toString(CharsetUtil.UTF_8);
            foundStart = false;
            foundType = false;
            foundLength = false;
            out.add(new NetMessage(curStart,curType,curLength,content));
        }
    }
}
